#include "GLSApplication.h"
#include <iostream>

GLSApplication::GLSApplication()
{
    
}
GLSApplication::~GLSApplication()
{
    
}


GLFWwindow* GLSApplication::GetWindowHandle()
{
    return m_pWindow;
}

int GLSApplication::Create(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share)
{
    m_pWindow = glfwCreateWindow(width, height, title, monitor, share);
    if (m_pWindow == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(m_pWindow);
    
    return 0;
}

int GLSApplication::GetWidth()
{
    int width,height;
    glfwGetWindowSize(m_pWindow, &width, &height);
    return width;
}

int GLSApplication::GetHeight()
{
    int width,height;
    glfwGetWindowSize(m_pWindow, &width, &height);
    return height;
}
void GLSApplication::SetState(unsigned int type)
{
    glEnable(type);
}

void GLSApplication::OnRender()
{

    /* Render here */
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
//    glBegin(GL_TRIANGLES);
//    
//    glColor3f(1.0f, 0.0f, 0.0f);
//    glVertex3f(0.0f, 1.0f, 0.0f);
//    
//    glColor3f(0.0f, 1.0f, 0.0f);
//    glVertex3f(-1.0f, -1.0f, 0.0f);
//    
//    glColor3f(0.0f, 0.0f, 1.0f);
//    glVertex3f(1.0f, -1.0f, 0.0f);
//    
//    glEnd();
    
    
}
void GLSApplication::OnInit()
{
    
}
void GLSApplication::OnInput()
{
    auto window = GetWindowHandle();
    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

void GLSApplication::OnSizeChanged(int width, int height)
{
    glViewport(0, 0, width, height);
    
}

int GLSApplication::Run()
{
    _AddApp(m_pWindow, this);
    
    //init
    OnInit();
    
    while (!glfwWindowShouldClose(m_pWindow))
    {
        // input
        OnInput();
        
        // render
        OnRender();
        
        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(m_pWindow);
        glfwPollEvents();
    }
    
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    
    _RemoveApp(m_pWindow);
    return 0;
}
